#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
   入口程序
"""

from app import create_app
from flask_script import Manager
from flask_script import Server
from flask import request, jsonify,g
from flasgger import Swagger
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from utils.response_code import RET

# 创建flask的app对象
app = create_app("develop")
SecretKey = app.config["SECRET_KEY"]
manager = Manager(app)
swagger = Swagger(app)


# 创建全站拦截器,每个请求之前做处理
@app.before_request
def user_require_token():
    # 不需要token验证的请求点列表
    permission = ['apiversion.apiversion', 'careInfo.careInfo', 'careInfo.careInfo_list', 'careInfo.careInfo_query',
                  'collectionInfo.collectionInfo', 'careInfo.careInfo_addcare', 'careInfo.careInfo_getcare',
                  'careInfo.careInfo_getcarelist', 'careInfo.careInfo_getsinglecare',
                  'collectionInfo.collectionInfo_list', 'collectionInfo.collectionInfo_query',
                  'collectionInfo.collectionInfo_collect', 'collectionInfo.collectionInfo_getcollectinfo',
                  'commentInfo.commentInfo', 'commentInfo.commentInfo_list', 'commentInfo.commentInfo_query',
                  'commentInfo.commentInfo_getallcomment', 'commentInfo.commentInfo_addcomment',
                  'commentInfo.commentInfo_messageinform',
                  'historyInfo.historyInfo', 'historyInfo.historyInfo_list', 'historyInfo.historyInfo_query',
                  'historyInfo.historyInfo_addhistory',
                  'passageInfo.passageInfo', 'passageInfo.passageInfo_list', 'passageInfo.passageInfo_query',
                  'passageInfo.passageInfo_userpublish', 'passageInfo.passageInfo_userread',
                  'passageInfo.passageInfo_pic', 'passageInfo.passageInfo_getoneall',
                  'passageInfo.passageInfo_fuzzyquery', 'passageInfo.passageInfo_recommend',
                  'passageInfo.passageInfo_toprecommend', 'passageInfo.passageInfo_deptquery','passageInfo.passageInfo_deletepassage',
                  'passageInfo.passageInfo_updatev1', 'passageInfo.passageInfo_updatev2', 
                  'recommandInfo.recommandInfo', 'recommandInfo.recommandInfo_list',
                  'recommandInfo.recommandInfo_query',
                  'upvoteInfo.upvoteInfo', 'upvoteInfo.upvoteInfo_list', 'upvoteInfo.upvoteInfo_query',
                  'upvoteInfo.upvoteInfo_upvote', 'upvoteInfo.upvoteInfo_cancelupvote','userInfo.userInfo_loginv1',
                  'userInfo.userInfo', 'userInfo.userInfo_list', 'userInfo.userInfo_query', 'userInfo.userInfo_login', 'userInfo.userInfo_myquery','userInfo.userInfo_getverifycode',
                  'userInfo.userInfo_commentme', 'userInfo.userInfo_upvoteme', 'userInfo.userInfo_replyme','userInfo.userInfo_search_byname','userInfo.userInfo_recommend',
                  'adminInfo.adminInfo', 'adminInfo.adminInfo_list', 'adminInfo.adminInfo_query','adminInfo.adminInfo_login','adminInfo.adminInfo_getpassageinfo',
                  'accuseInfo.accuseInfo', 'accuseInfo.accuseInfo_list', 'accuseInfo.accuseInfo_query',
                  'flasgger.apidocs', 'flasgger.static', 'flasgger.apispec_1', 'flasgger.<lambda>',

                  'passageInfo.passageInfo_vulnerability_6', 'passageInfo.passageInfo_userpublish_vulnerability_3', 'passageInfo.passageInfo_userread_vulnerability_3']
    print(request.endpoint)
    # 如果不是请求上述列表中的接口，需要验证token
    if request.endpoint not in permission:
        # 在请求头上拿到token
        token = request.headers.get("Token")
        if not all([token]):
            return jsonify(code=RET.PARAMERR, message="缺少参数Token或请求非法")

        # 校验token格式正确与过期时间
        s = Serializer(app.config["SECRET_KEY"])
        try:
            data = s.loads(token)
            #定义该请求中的全局变量
            g.user = data
        except Exception as e:
            app.logger.error(e)
            # 单平台用户登录失效
            return jsonify(code=RET.SESSIONERR, message='用户未登录或登录已过期')


# 创建全站拦截器，每个请求之后根据请求方法统一设置返回头
@app.after_request
def process_response(response):
    allow_cors = ['OPTIONS', 'PUT', 'DELETE', 'GET', 'POST']
    from flask import jsonify
    # 捕获flask_limiter的频率限制返回,ratelimit暂时无法捕获
    if response.status == '429 TOO MANY REQUESTS':
        response = {"code": RET.REQERR, "error": "该ip一定时间内请求过多,暂时拒绝访问", "message": "该ip一定时间内请求过多,暂时拒绝访问"}
        response = jsonify(response)
    if request.method in allow_cors:
        response.headers["Access-Control-Allow-Origin"] = '*'
        if request.headers.get('Origin') and request.headers['Origin'] == 'http://api.youwebsite.com':
            response.headers["Access-Control-Allow-Origin"] = 'http://api.youwebsite.com'

        response.headers["Access-Control-Allow-Credentials"] = 'true'
        response.headers['Access-Control-Allow-Methods'] = 'OPTIONS,GET,POST,PUT,DELETE'
        response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type,Token'
        response.headers['Access-Control-Expose-Headers'] = 'VerifyCodeID,ext'
    return response


if __name__ == "__main__":
    manager.run()
